package org.hongbo.springbootebsapi.interceptor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.hongbo.springbootebsapi.annotations.AllowRespInfoNull;
import org.hongbo.springbootebsapi.enums.ResultCode;
import org.hongbo.springbootebsapi.exceptions.BusinessException;
import org.hongbo.springbootebsapi.jwt.JwtTokenUtil;
import org.hongbo.springbootebsapi.result.PlatformResult;
import org.hongbo.springbootebsapi.util.ResponseResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Slf4j
public class AllowRespInfoNullInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(AllowRespInfoNull.class)) {
                log.info(" clazz.isAnnotationPresent(AllowRespInfoNull.class) ");
            } else if (method.isAnnotationPresent(AllowRespInfoNull.class)) {
                log.info(" method.isAnnotationPresent(AllowRespInfoNull.class) ");
            } else{
                if(!jwtTokenUtil.validRespInfo()){
//                    ResponseResultUtil.print(response , HttpServletResponse.SC_OK, PlatformResult.failure(ResultCode.PERMISSION_NEED_RESP_INFO));
//                    return false;
                    throw new BusinessException(ResultCode.PERMISSION_NEED_RESP_INFO);
                }

            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // nothing to do
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // nothing to do
    }



}
